package com.android.meige.fragment.group;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.utils.ConstantsUrl;
import com.android.meige.R;
import com.android.meige.activity.BaseObject;
import com.android.meige.fragment.BaseLazyFragment;
import com.android.meige.model.group.TopicListData;
import com.android.meige.model.group.TopicListDataCallback;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.group.VRefreshLayout;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/8/15.
 */

public class Fragment_ChoiceTopic extends BaseLazyFragment {
    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;

    private boolean networkConnected;
    private RelativeLayout progress;
    private View view;
    private FragmentActivity mcontext;
    private ArrayList<TopicListData.DataBean.ListBean> listdata = new ArrayList<>();
    private LayoutInflater inflater;
    private Adapt adapter;
    private VRefreshLayout mRefreshLayout;
    private LinearLayoutManager mLayoutManager;
    private CustomRecycleView mRecyclerView;

    public static Fragment_ChoiceTopic newInstance() {
        Fragment_ChoiceTopic fragment = new Fragment_ChoiceTopic();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.layout_choicetopic_refresh, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        initUI();
        ReFreshData();
        return view;
    }

    @Override
    protected void initPrepare() {

    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            GetTopicList();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    /**
     * 刷新
     */
    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                GetTopicList();
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    /**
     * 控件初始化
     */
    private void initUI() {
        mRefreshLayout = (VRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mRecyclerView = (CustomRecycleView) view.findViewById(R.id.listView);
        progress = (RelativeLayout) view.findViewById(R.id.progress);
        adapter = new Adapt(mcontext, listdata, "0");
        mLayoutManager = new LinearLayoutManager(mcontext);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
//        ((TextView) view.findViewById(R.id.scroll_total)).setText();
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
    }


    private void GetTopicList() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.TOPIC_LISTS;

            HttpUtils.get(address, null, new TopicListDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(TopicListData response, int id) {
                    if(response == null){
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata.clear();
                        TopicListData.DataBean data = response.getData();
                        if (data != null && ObjectUtils.listHasData(data.getList())) {
                            listdata.addAll(data.getList());
                            adapter.setNewData(listdata);
                        }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                        noDataTv.setText(response.getMsg());
                    }
                }
            });
        } else {
            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }

    public class Adapt extends BaseMultiItemQuickAdapter<TopicListData.DataBean.ListBean, BaseViewHolder> {
        private LayoutInflater Inflater;
        private Context content;

        public Adapt(Context content, List<TopicListData.DataBean.ListBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.thematicactivity_insert_horizontallist);
            this.content = content;
            this.Inflater = LayoutInflater.from(content);
        }

        @Override
        protected void convert(BaseViewHolder holder, final TopicListData.DataBean.ListBean ta_insert) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    holder.getView(R.id.progress_hot).setVisibility(View.INVISIBLE);
                    TextView more_tv = (TextView) holder.getView(R.id.more_tv);
                    TextView hotactivity_title = (TextView) holder.getView(R.id.hotactivity_title);
                    hotactivity_title.setText(ta_insert.getName());
                    //水平滚动列表
                    NestFullListView tabrow = (NestFullListView) holder.getView(R.id.grid);
                    //        //动态设置选项卡宽度，超过2个可以滑动查看
                    DisplayMetrics metrics = new DisplayMetrics();
                    mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                    int width = (int) (metrics.widthPixels / 2.5);
                    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
                    tabrow.setAdapter(new NestFullListViewAdapter<TopicListData.DataBean.ListBean.Apply_listBean>(R.layout.list_main_hor_adapter, ta_insert.getApply_list()) {
                        @Override
                        public void onBind(int position, TopicListData.DataBean.ListBean.Apply_listBean testBean, NestFullViewHolder holder) {
                            (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                            ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                            String price1 = testBean.getTeam_price();
                            SpannableString msp = new SpannableString("￥" + price1);
                            msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                            holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());
                            holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                            ObjectUtils.photo2(mcontext, testBean.getImg_src(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));

                        }
                    });

                    tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                        @Override
                        public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                            ObjectUtils.ToDetailActivity(mcontext, 1, ta_insert.getApply_list().get(pos).getId(), "");
                        }
                    });
                    more_tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(mcontext, BaseObject.class);
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, ta_insert.getId());
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "专题活动");
                            intent.putExtra("topicname", ta_insert.getName());
                            mcontext.startActivity(intent);
                        }
                    });

                    break;
            }
        }
    }
}
